#! /usr/bin/env python

def options(opt):
	opt.load('compiler_c')

def configure(conf):
	conf.load('compiler_c')
	conf.find_program('ldd')
	conf.where_is_shlib(lib='m')

# --- support code below ---

import re
from waflib import Task, TaskGen, Configure

class ldd_run(Task.Task):
	color = 'PINK'
	run_str = '${LDD} ${SRC} > ${TGT}'

	def post_run(self):
		ret = Task.Task.post_run(self)
		libname = self.generator.lib
		re_libpath = re.compile('lib%s.*\s+=>\s+(\S+%s\S+)\s+' % (libname, libname), re.M)
		m = re_libpath.search(self.outputs[0].read())
		if m:
			self.generator.tmp.append(m.group(1))
		else:
			return ret or 1
		return ret

@TaskGen.feature('ldd_check')
@TaskGen.after_method('apply_link')
def do_ldd_check(self):
	self.create_task('ldd_run', self.link_task.outputs[0], self.path.find_or_declare('ldd.out'))

@Configure.conf
def where_is_shlib(self, lib):
	tmp = []
	def check_msg(self):
		return tmp[0]

	self.check(
		fragment  = 'int main() { return 0; }\n',
		features  = 'c cprogram ldd_check',
		lib       = lib,
		linkflags = '-Wl,--no-as-needed',
		msg       = 'Where is library %r' % lib,
		define    = 'LIBFROM',
		tmp       = tmp,
		okmsg     = check_msg)

	return tmp[0]

